/*
 *   Copyright 2008 Francois Fernandes
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
package com.googlecode.opendoclibrary.server.internal.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

import com.googlecode.opendoclibrary.server.IDataHandle;

public class DataHandle implements IDataHandle
{
    private final File data;

    public DataHandle( InputStream is ) throws IOException
    {
        data = File.createTempFile( "odl-data-handle", "tmp" );
        data.deleteOnExit();
        OutputStream out = new FileOutputStream( data );
        byte[] buf = new byte[1024];
        int read;

        while ( ( read = is.read( buf ) ) >= 0 )
        {
            out.write( buf, 0, read );
        }
        out.flush();
        out.close();
    }

    @Override
    public InputStream asInputStream() throws IOException
    {
        ensureNotDisposed();
        return new FileInputStream( data );
    }

    @Override
    public RandomAccessFile asRandomAccessFile() throws IOException
    {
        ensureNotDisposed();
        return new RandomAccessFile( data, "r" );
    }

    private boolean disposed;

    protected void ensureNotDisposed() throws IllegalStateException
    {
        if ( disposed )
            throw new IllegalStateException( "DataHandle has already been disposed" );
    }

    public void dispose() throws IllegalStateException
    {
        ensureNotDisposed();
        if ( !data.delete() )
            if ( !data.delete() )
                data.delete();
    }
}
